using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using mEdit.Controls;
using mEdit.Properties;
using System.IO;

namespace mEdit
{
    public partial class MainForm : Form
    {
        #region Variables

        //private bool _contentChanged = false;

        #endregion

        bool _newFile = false;
        bool _nodeRemoved = false;


        #region auto-generated

        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			openFileDialog.Filter = Resources.AppFileFilter;
            if ( !string.IsNullOrEmpty( Properties.Settings.Default.LastDirectory ) )
                openFileDialog.InitialDirectory = Properties.Settings.Default.LastDirectory;
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                OpenFile(openFileDialog.FileName);
            }
        }

        private void OpenFile(string filename)
        {
            this._newFile = true;

            tvNodes.Load(filename);
            Properties.Settings.Default.LastOpenedFile = filename;
            Properties.Settings.Default.LastDirectory = Path.GetDirectoryName(filename);
            this.Text = String.Format("{0} - [ {1} ]", Resources.AppTitle, filename);

        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			saveFileDialog.Filter = Resources.AppFileFilter;
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                tvNodes.Save(saveFileDialog.FileName);
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

		private void CutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.editor.CutSelectedTextIntoClipboard();
		}

		private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.editor.CopySelectedTextIntoClipboard();
		}

		private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.editor.PasteFromClipboard();
		}

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        #endregion 

        #region Variables

        //string _currentNodeName;
        
        //private bool 

        #endregion 

        # region TreeView

        //private void ShowFileContent()
        //{

        //}

        //private void tvNodes_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        //{
        //    //if ( _currentNodeName != e.Node.Name )
        //    //    ShowFileContent();
        //}

        #endregion

        #region selecting  editor / treeview 

        public void SelectTreeView()
        {
            this.tvNodes.Select();
        }

        public void SelectEditor()
        {
            this.editor.Focus();
        }

        #endregion

        private void tvNodes_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Insert:
                    if (e.Modifiers == Keys.Control)
                        this.tvNodes.AddChildNode();
                    else
                        this.tvNodes.AddRootNode();
                    break;

                case Keys.Enter:
                    break;

                case Keys.E:
                    if (e.Modifiers == Keys.Control)
                        this.tvNodes.RenameCurrentNode();
                    break;

                case Keys.Delete:
                    _nodeRemoved = true;
                    this.tvNodes.RemoveNode();
                    _nodeRemoved = false;
                    break;

                case Keys.S:
                    if (e.Modifiers == Keys.Control)
                        this.SaveNodes();
                    break;
            }
        }

        private void SaveNodes()
        {
            // save nodes
            this.tvNodes.Save();

            // restore position of the cursor in EditorTextBox
            this.editor.RestoreCursorPosition();
        }


        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog(this);
        }

        private void tvNodes_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if ((this.tvNodes.SelectedNode != null) )
            {
                if (!_newFile && !_nodeRemoved)
                {
                    this.tvNodes.SetLastSelectedNodeContent(editor.Text);
                }
                else
                {
                    _newFile = false;
                }
                this.tvNodes.LastSelectedNode = this.tvNodes.SelectedNode;
            }
            if ( tvNodes.SelectedNode != null )
                editor.Text = tvNodes.SelectedNode.Tag as string;
            
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            bool show = this.WindowState != FormWindowState.Minimized;
            if ( show )
            {
                Form f = this.ActiveMdiChild;
                if (f != null)
                    f.WindowState = FormWindowState.Maximized;
            }
            this.ShowInTaskbar = (this.WindowState != FormWindowState.Minimized);
        }

        private void mnuApplication_Opening(object sender, CancelEventArgs e)
        {

        }

        #region ContexMenu 'Application'

        private void tsmiClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tsmiHideRestore_Click(object sender, EventArgs e)
        {
            switch( this.WindowState )
            {
                case FormWindowState.Minimized:
                    this.WindowState = FormWindowState.Normal;
                    break;
                case FormWindowState.Maximized:
                    this.WindowState = FormWindowState.Normal;
                    break;
                case FormWindowState.Normal:
                    this.WindowState = FormWindowState.Minimized;
                    break;
            }
        }

        #endregion
        #region ContextMenu 'Nodes'

        private void tsmiRenameNode_Click(object sender, EventArgs e)
        {
            this.tvNodes.RenameCurrentNode();
        }

        private void tsmiAddNode_Click(object sender, EventArgs e)
        {
            this.tvNodes.AddChildNode();
        }

        private void tsmiDeleteNode_Click(object sender, EventArgs e)
        {
            this.tvNodes.RemoveNode();
        }

        private void tsmiAddRootNode_Click(object sender, EventArgs e)
        {
            this.tvNodes.AddRootNode();
        }

        private void tsmiAddSibling_Click(object sender, EventArgs e)
        {
            this.tvNodes.AddSiblingNode();
        }

        #endregion
        private void MainFormMDI_KeyDown(object sender, KeyEventArgs e)
        {
			if (e.KeyCode == Keys.S && e.Modifiers == Keys.Control)
				this.SaveNodes();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tvNodes_AfterSelect(null, null);
			this.SaveNodes();
        }

        private void ntfIcon_DoubleClick(object sender, EventArgs e)
        {
            tsmiHideRestore_Click(this, EventArgs.Empty);
        }

        private void editor_ContentChanged(object sender, EventArgs e)
        {
            //if (!_contentChanged)
            //{
            //    this.Text += " *";
            //    _contentChanged = true;
            //}
        }

        private void editor_ContentStored(object sender, EventArgs e)
        {
            //if (this._contentChanged)
            //{
            //    this.Text = this.Text.Remove(this.Text.Length - 2, 2);
            //    _contentChanged = false;
            //}
        }

		//private void SavePositionAndSize()
		//{

		//}

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Options options = new Options();
			options.CharSet = ScintillaNet.CharacterSet.EastEurope;
			options.EncodingName = Settings.Default.Encoding;

            if (options.ShowDialog(this) == DialogResult.OK)
            {
                this.editor.EditorForeColor = options.EditorForeColor;
                Properties.Settings.Default.EditorForeColor = options.EditorForeColor;
                this.editor.EditorBackColor = options.EditorBackColor;
                Properties.Settings.Default.EditorBackColor = options.EditorBackColor;
                this.editor.LinesBackColor = options.LineBackColor;
                Properties.Settings.Default.LineBackColor = options.LineBackColor;
                this.editor.LinesForeColor = options.LineForeColor;
                Properties.Settings.Default.LineForeColor = options.LineForeColor;
                this.editor.EditorFont = options.EditorFont;
                Properties.Settings.Default.EditorFont = options.EditorFont;
                //this.editor
                Properties.Settings.Default.GDICharSet = options.EditorFont.GdiCharSet;
				// encoding
				Properties.Settings.Default.Encoding = options.EncodingName;
				Properties.Settings.Default.Save();

				this.editor.SetEncodingsAndCharset(Settings.Default.Encoding, Settings.Default.GDICharSet, Settings.Default.EditorFont);
            }
        }

        private void SaveOptions()
        {
            Properties.Settings.Default.WindowSize = this.Size;
            Properties.Settings.Default.WindowPostion = this.Location;
			Settings.Default.MarginWidth = this.editor.LineNumberMarginWidth;
            Properties.Settings.Default.Save();
        }

        private void LoadOptions()
        {
            this.editor.EditorForeColor = Properties.Settings.Default.EditorForeColor;
            this.editor.EditorBackColor = Properties.Settings.Default.EditorBackColor;
            this.editor.LinesBackColor = Properties.Settings.Default.LineBackColor;
            this.editor.LinesForeColor = Properties.Settings.Default.LineForeColor;

			Font tempFont = Properties.Settings.Default.EditorFont;
			Font properFont = new Font(tempFont.FontFamily, tempFont.Size, tempFont.Style, tempFont.Unit, Properties.Settings.Default.GDICharSet);
			this.editor.EditorFont = properFont;

			this.Location = Properties.Settings.Default.WindowPostion != new Point(-1, -1) ? Properties.Settings.Default.WindowPostion : this.Location;
			this.Size = Properties.Settings.Default.WindowSize != new Size(-1, -1) ? Properties.Settings.Default.WindowSize : this.Size;
			this.editor.SetEncodingsAndCharset(Settings.Default.Encoding, Settings.Default.GDICharSet, Settings.Default.EditorFont);

			this.editor.LineNumberMarginWidth = Settings.Default.MarginWidth;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.LoadOptions();
			if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpenedFile))
				OpenFile(Properties.Settings.Default.LastOpenedFile);
			else
				this.Text = Resources.AppTitle;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.SaveOptions();
        }

        private void shortcutKeysToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShortcutKeys keys = new ShortcutKeys();
            keys.ShowDialog(this);
        }

    }
}